from django.shortcuts import render
from django.http import HttpRequest, HttpResponse, JsonResponse
import time
import simplejson
from .models import Result
from django.db import transaction
from urllib import parse
import re
from django.db import transaction


def input_results(request: HttpRequest):
    print(request.body)
    try:
        for result in simplejson.loads(request.body).get("results"):
            # 先看学号是否已经存在,存在则覆盖
            with transaction.atomic():
                obj = Result.objects.filter(stu_id=result.get("stu_id")).first()
                if obj:
                    obj.chinese = result.get("chinese")
                    obj.math = result.get("math")
                    obj.english = result.get("english")
                else:
                    obj = Result(stu_id=result.get("stu_id"), chinese=result.get("chinese"), math=result.get("math"),
                             english=result.get("english"))
                obj.save()
    except Exception as e:
        return HttpResponse(status=400)

    return HttpResponse(status=200)


def query_result(request: HttpRequest):
    try:
        stu_id = int(simplejson.loads(request.body).get("stu_id", 0))
        if stu_id:
            obj = Result.objects.filter(stu_id=stu_id).first()
            if obj:
                data = {"id": obj.id, "stu_id": obj.stu_id, "chinese": obj.chinese, "math": obj.math, "english": obj.english}
                print(data)
                return JsonResponse(data)
            else:
                return HttpResponse(status=402)
    except:
        return HttpResponse(status=400)


def get_all_result(request: HttpRequest):
    results = Result.objects.all()
    data_list = [{"key": result.id, "stu_id": result.stu_id, "chinese": result.chinese, "math": result.math, "english": result.english} for result in results]

    return JsonResponse({"data": data_list})


def check_role(request: HttpRequest):
    session = request.session
    if session.get("role") == "teacher":
        time.sleep(3)
        return HttpResponse(status=200)
    elif session.get("role") == "student":
        return HttpResponse(status=400)
    else:
        return HttpResponse(status=401)


def upload_result(request: HttpRequest):
    origin = parse.parse_qs(request.body.decode())
    middle: str = ""
    dest_dict = {}
    data = []

    try:
        with transaction.atomic():
            for key, val in origin.items():
                regx = re.compile("data\[\d+\]")
                match_obj = regx.match(key)
                if match_obj:
                    if middle == key[match_obj.start(): match_obj.end()]:
                        if key[match_obj.end() + 1:-1] == "stu_id":
                            dest_dict[key[match_obj.end() + 1:-1]] = int(val[0])
                        else:
                            dest_dict[key[match_obj.end() + 1:-1]] = float(val[0])
                    else:
                        if dest_dict.__len__() != 0:
                            data = append_result(data, dest_dict)

                        middle = key[match_obj.start(): match_obj.end()]
                        if key[match_obj.end() + 1:-1] == "stu_id":
                            dest_dict[key[match_obj.end() + 1:-1]] = int(val[0])
                        else:
                            dest_dict[key[match_obj.end() + 1:-1]] = float(val[0])

            data = append_result(data, dest_dict)
            return JsonResponse({"data": data})
    except Exception as e:
        return HttpResponse(status=400)


def append_result(data, dest_dict):
    result = Result(stu_id=dest_dict.get("stu_id"), chinese=dest_dict.get("chinese"),
                    math=dest_dict.get("math"), english=dest_dict.get("english"))
    result.save()
    data.append({"key": result.id, "stu_id": result.stu_id, "chinese": result.chinese,
                 "math": result.math, "english": result.english})
    return data